package org.dce.screencapturer.actions.objects;

import java.util.Set;

import javax.swing.Icon;

import org.dce.screencapturer.Drawing;
import org.dce.screencapturer.SelectionEvent;
import org.dce.screencapturer.SelectionListener;
import org.dce.screencapturer.actions.DrawingAction;
import org.dce.screencapturer.objects.DrawingObject;

@SuppressWarnings("serial")
public abstract class ObjectAction 
	extends DrawingAction 
	implements SelectionListener{
	
	private DrawingObject selectedObject;

	public ObjectAction(String category, String actionId) {
		this(category, actionId, null);
	}

	public ObjectAction(String category, String actionId, Icon icon) {
		super(category, actionId, icon);
		setEnabled(false);
	}
	
	@Override
	public void selectionChanged(SelectionEvent event) {
		Drawing drawing = getDrawing();
		
		selectedObject = null;
		
		if (drawing != null){
			Set<DrawingObject> selection = drawing.getSelectionHandler().getSelection();
			
			if (selection.size() == 1){
				DrawingObject selectedObject = selection.iterator().next();
				
				if (acceptObject(selectedObject)){
					this.selectedObject = selectedObject;
				}
			}
		}
		
		setEnabled(selectedObject != null);
	}
	
	protected DrawingObject getObject(){
		return selectedObject;
	}

	@Override
	public void setDrawing(Drawing drawing) {
		
		Drawing oldDrawing = getDrawing();
		
		if (oldDrawing != null){
			oldDrawing.getSelectionHandler().removeSelectionListener(this);
		}
		
		super.setDrawing(drawing);
		
		if (drawing != null){
			drawing.getSelectionHandler().addSelectionListener(this);
		}
	}

	protected abstract boolean acceptObject(DrawingObject anObject);


}
